package com.example.dangdangbackend.filter;

import com.example.dangdangbackend.common.BaseContext;
import com.example.dangdangbackend.common.CustomException;
import com.example.dangdangbackend.entity.Result;
import com.example.dangdangbackend.utils.JwtUtil;
import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;

import java.io.IOException;
import java.util.Map;
import java.util.Objects;


/**
 * 做登录拦截
 */
@Slf4j
public class LoginFilter implements Filter {

    public static final AntPathMatcher PATH_MATCHER = new AntPathMatcher();

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {

        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        String requestURI = request.getRequestURI();
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
        response.setHeader("Access-Control-Allow-Headers", "Content-Type, Authorization");


        log.info("拦截到请求:{}", requestURI);

        String[] urls = new String[]{
                "/static/**",
                "/user/**",
                "/category/**",
                "/common/**",
                "/book/**",
                "/trade/**",
                "/order/getOrderAndItemDetail",
                "/order/getOrderDetail"
        };

        boolean check = check(urls, requestURI);
        //不需要处理 直接放行
        if (check) {
            log.info("本次请求{}不需要处理", requestURI);
            filterChain.doFilter(request, response);

            return;
        }

        //处理 jwt令牌 看看是否需要放行
        String token = request.getHeader("jwt");
        if (token == null) {
            return;
        }
        if (!Objects.equals(token, "")) {
            try {
                Map<String, Object> UserInfo = JwtUtil.parseToken(token);
                //将token解析成一个键值对
                Integer id = (Integer) UserInfo.get("id");
                log.info("id为{}", id);
                BaseContext.setCurrentId(id);
            } catch (Exception e) {
                throw new CustomException("当前登录过期");
            }
            filterChain.doFilter(request, response);
            return;
        }

        log.info("用户未登录");
        response.getWriter().write(com.alibaba.fastjson.JSON.toJSONString(Result.error("NOTLOGIN")));
    }


    /**
     * 进行匹配，看看当前请求url是否需要进行放行
     *
     * @param urls
     * @param requestURI
     * @return
     */
    private boolean check(String[] urls, String requestURI) {
        for (String url :
                urls) {
            boolean match = PATH_MATCHER.match(url, requestURI);
            if (match) {
                return true;
            }
        }
        return false;
    }
}
